package com.xxx.base.util;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

public class FileUtils {
    protected final static Log log = Log.of(FileUtils.class);
    private static boolean success = false;
    /**
     * 上传文件
     * @param file
     * @return
     */
    public static boolean uploadFile (MultipartFile file) {
        if (file.isEmpty()) {
            return success;
        }
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：{0}" , fileName );
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = "D://temp//";
        File dest = new File(filePath + fileName);
        log.info("上传的文件路径为：{0}" , dest.getPath() );
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            success = true;
        } catch (IllegalStateException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }
        return success;
    }

    public static boolean downLoadFile (HttpServletRequest request,  HttpServletResponse response) {
        String fileName =request.getParameter("name");
        if (fileName != null) {
            String realPath = request.getServletContext().getRealPath(
                    "//WEB-INF//");
            File file = new File(realPath, fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                   success = true;
                } catch (Exception e) {
                    success = false;
                    log.error(e);
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            log.error(e);
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            log.error(e);
                        }
                    }
                }
            }
        }
        return  success;
    }

    public static boolean uploadMutliFile (HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                    success =true;
                } catch (Exception e) {
                    stream = null;
                    log.error("You failed to upload " + i + " => "
                            + e.getMessage());
                    success = false;
                }
            } else {
                log.error("You failed to upload " + i
                        + " because the file was empty.");
            }
        }
        return  success;
    }

}
